<?php

namespace app\admin\controller;

use think\facade\Request;
use app\admin\model\PermissionCategory AS CategoryModel;
use app\admin\validate\PermissionCategory AS CategoryValidate;

class PermissionCategory extends Base
{
    public function index()
    {
        $search = input('');
        $search = [
            'name' => isset($search['name']) ? $search['name'] : '',
            'status' => isset($search['status']) ? $search['status'] : -1,
        ];

        $where = [];
        if (!empty($search['name'])) {
            $where['name'] = $search['name'];
        }

        if ($search['status'] != null && $search['status'] != -1) {
            $where['status'] = $search['status'];
        }
        $model = CategoryModel::getList($where);
        return view('index', [
            'model' => $model['model'],
            'count' => $model['count'],
            'status' => CategoryModel::attributes('status'),
            'where' => $search
        ]);
    }

    public function form()
    {
        if (Request::instance()->isPost()) {
            $data = input('post.');

            // 检测变量
            $validate = new CategoryValidate();
            if (!$validate->check($data)) {
                return json(self::sendResult(102, [], $validate->getError()));
            }

            $res = CategoryModel::saveOne($data);
            return json(self::sendResult($res['code'], [
                'url' => url('index'),
            ], $res['msg']));

        } else {
            $id = input('id');
            $model = [];
            $title = '添加权限分组';
            if ($id > 0) {
                $title = '编辑权限分组';
                $model = CategoryModel::get($id);
            }
            return view('form', [
                'status' => CategoryModel::attributes('status'),
                'model' => $model,
                'title' => $title
            ]);
        }
    }

    public function delete($id)
    {
        CategoryModel::deleteOne($id);
        return self::sendResult(self::$okCode, [
            'url' => url('index'),
        ]);
    }
}